<template>
  <div class="indicator-config-container">
    <!-- 左侧目录树 -->
    <div class="left-panel">
      <IndicatorTree 
        ref="indicatorTreeRef"
        @node-select="handleNodeSelect"
        @data-loaded="handleIndicatorTreeLoaded"
      />
    </div>
    
    <!-- 右侧内容区域 -->
    <div class="right-panel">
      <!-- 左侧指标配置区域 -->
      <div class="config-panel">
        <div class="config-header">
          <h3 class="config-title">指标配置</h3>
          <el-button type="primary" size="small" @click="handleAddIndicator">
            添加指标
          </el-button>
        </div>
        <div class="config-tree">
          <IndicatorConfigTree 
            ref="configTreeRef"
            @node-click="handleConfigTreeClick"
            @data-loaded="handleConfigTreeLoaded"
          />
        </div>
      </div>
      
      <!-- 右侧表格区域 -->
      <div class="table-panel">
        <!-- 表格筛选条件 -->
        <div class="filter-bar">
          <div class="filter-left">
            <el-input
              v-model="filterForm.firstView"
              placeholder="一级视角"
              clearable
              style="width: 150px; margin-right: 10px;"
              @input="handleFilter"
            />
            
            <el-input
              v-model="filterForm.secondView"
              placeholder="二级视角"
              clearable
              style="width: 150px; margin-right: 10px;"
              @input="handleFilter"
            />
            
            <el-input
              v-model="filterForm.indexName"
              placeholder="搜索指标"
              clearable
              style="width: 200px;"
              @input="handleFilter"
            >
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
          </div>
        </div>
        
        <el-table 
          :data="tableData" 
          style="width: 100%" 
          height="100%"
          v-loading="tableLoading"
        >
          <el-table-column prop="firstView" label="一级视角" width="120" />
          <el-table-column prop="secondView" label="二级视角" width="120" />
          <el-table-column prop="indexName" label="指标名称" min-width="150" />
          <el-table-column prop="unit" label="指标单位" width="100" />
          <el-table-column prop="year" label="指标年份" width="100" />
          <el-table-column prop="style" label="样式" width="100" />
          <el-table-column prop="groupIndex" label="组" width="100" />
          <!-- <el-table-column label="操作" width="150">
            <template #default="{ row, $index }">
              <el-button size="small" @click="handleEdit(row, $index)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(row, $index)">删除</el-button>
            </template>
          </el-table-column> -->
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    
    <!-- 添加指标弹窗 -->
    <AddIndicatorDialog
      v-if="showAddDialog"
      v-model="showAddDialog"
      :pre-selected-ids="selectedIndicatorIds"
      :area-code="areaCode[0]"
      :catalog-id="catalogId"
      @confirm="handleConfirmAdd"
    />
  </div>
</template>

<script>
import IndicatorTree from './components/IndicatorTree.vue'
import IndicatorConfigTree from './components/IndicatorConfigTree.vue'
import AddIndicatorDialog from './components/AddIndicatorDialog.vue'
import { 
  addIndicatorConfig, 
  queryConfigByDistrictAndCatalog, 
  queryConfigByDistrictAndCatalogSelected 
} from '@/api/screen-management/indicator-config'

export default {
  name: 'IndicatorConfig',
  components: {
    IndicatorTree,
    IndicatorConfigTree,
    AddIndicatorDialog
  },
  data() {
    return {
      selectedNode: null,
      selectedTreeNode: null,
      // 表格相关数据
      tableData: [],
      tableLoading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      showAddDialog: false,
      selectedIndicatorIds: [], // 已选中的指标ID数组
      // 筛选表单
      filterForm: {
        firstView: '',
        secondView: '',
        indexName: ''
      },
      // 树组件加载状态
      treeLoadedStatus: {
        indicatorTree: false,
        configTree: false
      },
      areaCode: [],
      catalogId: '',
      selectedAreaCode: '',
    }
  },
  mounted() {
    // 等待组件渲染完成后初始化默认选中
    this.$nextTick(() => {
      this.initDefaultSelection()
    })
  },
  methods: {
    // 初始化默认选中
    initDefaultSelection() {
      this.checkAndSelectDefault()
    },
    
    // 处理IndicatorTree数据加载完成
    handleIndicatorTreeLoaded(data) {
      this.treeLoadedStatus.indicatorTree = true
      this.checkAndSelectDefault()
    },
    
    // 处理IndicatorConfigTree数据加载完成
    handleConfigTreeLoaded(data) {
      this.treeLoadedStatus.configTree = true
      this.checkAndSelectDefault()
    },
    
    // 检查并选中默认节点
    checkAndSelectDefault() {
      if (this.treeLoadedStatus.indicatorTree && this.treeLoadedStatus.configTree) {
        this.$nextTick(() => {
          this.selectDefaultTreeNodes()
        })
      }
    },
    
    // 选中两个树的第一个节点
    selectDefaultTreeNodes() {
      try {
        const indicatorTreeRef = this.$refs.indicatorTreeRef
        if (indicatorTreeRef && indicatorTreeRef.treeData && indicatorTreeRef.treeData.length > 0) {
          const firstIndicatorNode = indicatorTreeRef.treeData[0]
          indicatorTreeRef.setSelectedNode(firstIndicatorNode)
        }
        
        // 选中IndicatorConfigTree的第一个节点
        const configTreeRef = this.$refs.configTreeRef
        if (configTreeRef && configTreeRef.treeData && configTreeRef.treeData.length > 0) {
          const firstConfigNode = configTreeRef.treeData[0]
          configTreeRef.$refs.treeRef.setCurrentKey(firstConfigNode.pkid)
        }
        this.selectedAreaCode = configTreeRef.treeData[0].pkid
        this.catalogId = indicatorTreeRef.treeData[0].pkid
        
        // 延迟加载表格数据，确保树选中状态生效
        this.$nextTick(() => {
          this.loadTableData()
        })
        
      } catch (error) {
        console.error('初始化默认选中失败:', error)
      }
    },
    
    // 处理目录树节点选择
    handleNodeSelect(data, node) {
      this.selectedNode = data
      this.selectedTreeNode = node
      this.loadTableData()
    },
    
    // 处理配置树点击
    handleConfigTreeClick(data) {
      this.selectedAreaCode = data.pkid
      this.loadTableData()
    },
    
    // 添加指标
    handleAddIndicator() {
      const currentNode = this.$refs.configTreeRef.getCurrentNode()?.pkid
      // this.areaCode = this.$refs.configTreeRef.getCurrentNode()?.pkid
      this.areaCode = this.$refs.configTreeRef
                     .getCurrentNodeCheck() 
                     .map(node => node.pkid)
      this.catalogId = this.$refs.indicatorTreeRef.getSelectedNode()?.data?.pkid
      
      if (!this.areaCode.length || !this.catalogId) {
        this.$message.warning('请先选择目录和区域')
        return
      }

      if (this.areaCode.length > 1) {
        // 批量操作确认弹窗
        this.$confirm('批量操作时被选中项的所有关联指标都将以此次勾选为准，是否要进行此操作？', '确认批量操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 用户确认后，执行添加指标操作
          this.proceedWithAddIndicator(currentNode)
        }).catch(() => {
          // 用户取消，不做任何操作
          this.$message.info('已取消批量操作')
        })
        return
      }
      
      // 单个区域的情况，直接执行
      this.proceedWithAddIndicator(currentNode)
    },

    // 执行添加指标操作
    proceedWithAddIndicator(currentNode) {
      // 先获取已选中的指标ID，然后打开弹窗
      const requestParams = {
        areaCode: this.areaCode[0],
        catalogId: this.catalogId
      }
      
      queryConfigByDistrictAndCatalogSelected(requestParams).then(res => {
        if (res.success) {
          const selectedIndex = res.data || []
          this.selectedIndicatorIds = selectedIndex
          this.showAddDialog = true
        } else {
          this.selectedIndicatorIds = []
          this.showAddDialog = true
        }
      }).catch(err => {
        // 即使获取失败，也允许打开弹窗
        this.selectedIndicatorIds = []
        this.showAddDialog = true
      })
    },
    
    // 确认添加指标
    handleConfirmAdd(selectedData) {
      // 获取IndicatorTree的选中值
      const indicatorTreeSelected = this.$refs.indicatorTreeRef.getSelectedNode()?.data?.pkid
      
      // 获取IndicatorConfigTree的选中值
      // const configTreeSelected = this.$refs.configTreeRef.getCurrentNode()?.map(node => node.pkid)

      // if (selectedData.length > 0) { 
        addIndicatorConfig({
          areaCode: this.areaCode,
          catalogId: indicatorTreeSelected,
          indexRelDetails: selectedData.map(item => {
            return {
              indexId: item.pkid || item.id,
              indexType: item.type || '',
              style: item.style || '',
              groupIndex: item.groupIndex || '',
              orderIndex: Number(item.orderIndex) || 0
            }
          })
        }).then(res => {
        if (res.success) {
          this.$message.success(`成功添加 ${selectedData.length} 个指标配置`)
          
          this.loadTableData()
          // 清空 IndicatorConfigTree 的选中状态
          this.$refs.configTreeRef.clearCheckedNodes()
        }
        }).catch(err => {
          this.$message.error('指标配置添加失败')
        })
      //  } else {
      //    this.$message.warning('请先选择目录和区域')
      //  }
    },
    
    // 编辑指标
    handleEdit(row, index) {
      this.$message.info('编辑指标功能待实现')
    },
    
    // 删除指标
    handleDelete(row, index) {
      this.$confirm('确定要删除这个指标吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableData.splice(index, 1)
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val
      this.loadTableData()
    },
    
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadTableData()
    },
    
    // 加载表格数据
    loadTableData() {
        // const areaCode = this.$refs.configTreeRef?.getCurrentNode()?.map(node => node.pkid)
        // console.log('areaCode :>> ', areaCode)
        const catalogId = this.$refs.indicatorTreeRef?.getSelectedNode()?.data?.pkid
        if (this.selectedAreaCode && catalogId) {
          const params = {
            areaCode: this.selectedAreaCode,
            catalogId: catalogId,
            pageSize: this.pageSize,
            pageIndex: this.currentPage
          }
          
          // 添加筛选参数
          if (this.filterForm.firstView) {
            params.firstView = this.filterForm.firstView
          }
          if (this.filterForm.secondView) {
            params.secondView = this.filterForm.secondView
          }
          if (this.filterForm.indexName) {
            params.indexName = this.filterForm.indexName
          }
          
          this.tableLoading = true
          
          queryConfigByDistrictAndCatalog(params).then(res => {
            if (res.success) {
              this.tableData = res.data.list || []
              this.total = res.data.count || 0
            }
          }).catch(err => {
            console.error('查询失败:', err)
            this.tableData = []
            this.total = 0
          }).finally(() => {
            this.tableLoading = false
          })
        } else {
          this.tableData = []
          this.total = 0
        }
      // this.tableLoading = true
      // // 模拟异步加载
      // setTimeout(() => {
      //   this.total = this.tableData.length
      //   this.tableLoading = false
      // }, 300)
    },
    
    // 处理筛选
    handleFilter() {
      // 重置到第一页
      this.currentPage = 1
      // 重新加载数据
      this.loadTableData()
    },
    
    // 获取当前选中的节点（暴露给外部使用）
    getSelectedNode() {
      return {
        data: this.selectedNode,
        node: this.selectedTreeNode
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.indicator-config-container {
  height: 100%;
  display: flex;
  background-color: #f5f7fa;
  
  .left-panel {
    width: 300px;
    background-color: #ffffff;
    border-right: 1px solid #ebeef5;
    padding: 20px;
    overflow: hidden;
  }
  
  .right-panel {
    flex: 1;
    display: flex;
    // padding-left: 20px;
    // gap: 20px;
    overflow: hidden;
    
    // 左侧配置面板
    .config-panel {
      width: 200px;
      background-color: #ffffff;
      border-radius: 4px;
      padding: 16px;
      display: flex;
      flex-direction: column;
      border: 1px solid #ebeef5;
      
      .config-header {
        display: flex;
        flex-direction: column;
        gap: 12px;
        margin-bottom: 16px;
        
        .config-title {
          margin: 0;
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
      }
      
      .config-tree {
        flex: 1;
        overflow: auto;
      }
    }
    
    // 右侧表格面板
    .table-panel {
      flex: 1;
      background-color: #ffffff;
      border-radius: 4px;
      padding: 20px;
      border: 1px solid #ebeef5;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      
      .filter-bar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 0;
        border-bottom: 1px solid #ebeef5;
        margin-bottom: 16px;
        
        .filter-left {
          display: flex;
          align-items: center;
        }
      }
      
      .pagination-wrapper {
        margin-top: 16px;
        display: flex;
        justify-content: flex-end;
        padding-top: 16px;
        border-top: 1px solid #ebeef5;
      }
    }
  }
}
</style>